'use strict'

import { app, protocol, BrowserWindow, ipcMain, Menu, MenuItem, ipcRenderer, globalShortcut } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import util  from './utils/util'

const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let win = null;
async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 900,
    minWidth:900,
    height: 600,
    minHeight: 300,
    webPreferences: {
      
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      contextIsolation: false,
    }
  })
  // win.webContents.insertCSS(`
  //   ::-webkit-scrollbar {
  //     display: none;
  //   }
  // `)
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    util.StopLogProcess()
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {

const existingMenu = Menu.getApplicationMenu();
  const targetItem = {
    label: 'Target',
    submenu: [
    ]
  }
  existingMenu.append(new MenuItem(targetItem));
  Menu.setApplicationMenu(existingMenu)

  createWindow()
  ipcMain.handle('Ipc::StartLog', StartLogHandler)
  ipcMain.handle('Ipc::StopLog', StopLogHandler)
  UpdateTargets()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        util.StopLogProcess()
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      util.StopLogProcess()
      app.quit()
    })
  }
}

function callback(data){
 win.webContents.send('View::ReceiveLog', data)
}

function StartLogHandler(event, jsonParam){
  console.log('start log ', jsonParam)
  util.StartLog(jsonParam, callback)
}

function StopLogHandler(event) {
  console.log('stop process')
  util.StopLogProcess()
}
function updateTargetsCallback(data) {
  const targets = data.split(/\r?\n/);
  const len = targets.length
  const existingMenu = Menu.getApplicationMenu();
  const targetMenu = existingMenu.items.find(item => item.label === 'Target');
  if(!targetMenu) {
    return
  }
  targetMenu.submenu.clear()
  for(let i = 0; i < len-1; i++) {
     targetMenu.submenu.append(
        new MenuItem({
            label: `${targets[i]}`,
            click: () => {
                console.log(`点击了 ${targets[i]} `);
                win.webContents.send('View::SetSelectedTarget', targets[i])
            }
        })
    );
  }
   Menu.setApplicationMenu(existingMenu);
}

function UpdateTargets(){
  util.UpdateTargets(updateTargetsCallback)
}